package com.cc.police.controller;

import com.cc.police.config.LoginRequired;
import com.cc.police.entity.Cpu;
import com.cc.police.entity.PUpdate;
import com.cc.police.mapper.PPoliceMapper;
import com.cc.police.mapper.PUpdateMapper;
import com.cc.police.service.PPoliceService;
import com.cc.police.util.RedisUtil;
import com.cc.police.util.excelUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/influx")
@CrossOrigin//前后端请求跨域注解
public class CeshiController {
    @Autowired
    private InfluxDB influxDB;
    @Autowired
    PPoliceMapper mapper;
    @Autowired
    PUpdateMapper updateMapper;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    PPoliceService pPoliceService;


//
//        @Scheduled(fixedRate = 5000)
//        public void reportCurrentTime() {
//        //定时任务注解把把v
//            System.err.println("现在时间0：" +new Date());
//
//        }
//
//    @Scheduled(fixedRate = 5000)
//    public void reportCurrentTime1() {
//        //定时任务注解
//        System.out.println("现在时间1：" +new Date());
//
//    }
//
//    @Scheduled(fixedRate = 5000)
//    public void reportCurrentTime2() {
//        //定时任务注解
//        System.err.println("现在时间2：" +new Date());
//
//    }
//
//    @Scheduled(fixedRate = 5000)
//    public void reportCurrentTime3() {
//        //定时任务注解
//        System.out.println("现在时间3：" +new Date());
//
//    }
//
//    @Scheduled(fixedRate = 5000)
//    public void reportCurrentTime4() {
//        //定时任务注解
//        System.err.println("现在时间4：" +new Date());
//
//    }
//
//    @Scheduled(fixedRate = 5000)
//    public void reportCurrentTime5() {
//        //定时任务注解
//        System.out.println("现在时间5：" +new Date());
//
//    }
//
//    @Scheduled(fixedRate = 5000)
//    public void reportCurrentTime7() {
//        //定时任务注解
//        System.err.println("现在时间7：" +new Date());
//
//    }



//    @Scheduled(fixedRate = 5000)
    @GetMapping("/getsAll")
    @LoginRequired(loginSuccess = true)
    public void test() throws InterruptedException {
//        String sql = "select * from \"7S_2A_Current_Feed\"";
//        String sql = "select * from "+ "\"7S_2A_Current_Feed\"";
        long date = new Date().getTime();
        System.err.println(date);
        List<Cpu> trackPoints = new ArrayList<>();

//        List data =  excelUtil.excel();
//        System.out.println("数据条数="+data.size());
//        System.out.println("集合数据="+data);

        List<PUpdate> pUpdate = updateMapper.selectAll();
//        System.out.println("size= "+pUpdate.size());
//        System.out.println("shuju="+pUpdate);
//        System.out.println("cariable= "+pUpdate.get(0).getVariable());
//        System.out.println("cariable= "+pUpdate.get(11).getVariable());
//        System.out.println("cariable= "+pUpdate.get(12).getVariable());
//        System.out.println("cariable= "+pUpdate.get(13).getVariable());

        for (int j = 0; j < pUpdate.size(); j++) {
//            Thread thread = new Thread();
//            Thread.sleep(1000);
//            System.out.println("cariable= "+pUpdate.get(j));
            String sql = "select * from "+ "\""+pUpdate.get(j).getVariable()+"\"";
//            String sql = "select * from "+ "\""+pUpdate.get(j).getVariable()+"\""+"WHERE time > now() - 1m";

//            System.err.println("sql语句"+sql);

            Query query = new Query(sql,"gydb");
            influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
            //毫秒输出
            QueryResult queryResult = influxDB.query(query, TimeUnit.MILLISECONDS);
            List<QueryResult.Result> resultList =  queryResult.getResults();

            String sss = queryResult.toString();

            //把查询出的结果集转换成对应的实体对象，聚合成list

            for(QueryResult.Result result:resultList){
                List<QueryResult.Series> seriesList = result.getSeries();
                if(seriesList==null){
                    break;
                }else {
                    for(QueryResult.Series series : seriesList){
                        String name = series.getName();
                        Map<String, String> tags = series.getTags();
                        List<String> columns = series.getColumns();
                        String[] keys =  columns.toArray(new String[columns.size()]);
                        List<List<Object>> values = series.getValues();
                        for(List<Object> value:values){
                            Map beanMap = new HashMap();
                            Cpu point = new Cpu();
                            for (int i = 0; i < keys.length; i++) {
                                beanMap.put(keys[i],value.get(i));
                            }
                            try {
                                //查询的时候没用，写入point的时候用
                                Point po = Point.measurement("trackpoint").fields(beanMap).build();
                                //time 默认存入的是UTC格式  2020-04-29T22:58:23.58978834，默认转换成String
                                //{"cpuid":"11","cputype":"H","lat":"10.111222","lon":"78.000111","state":"on","time":"2020-04-29T22:57:06.732701567Z"}
                                BeanUtils.populate(point,beanMap );
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            }

                            //调用方法
//                        Variable.variable(data.get(j),point.getValue());
//                            variable(pUpdate.get(j).getVariable(),point.getValue());

                            String o = pUpdate.get(j).getVariable();
                            double valuess = point.getValue();
                            String blname = String.valueOf(o);  //变量名字是数据库名
                            String svalue = String.valueOf(valuess);  //查询的报警value值
                            Date data = new Date();
                            Jedis jedis = redisUtil.getJedis();

                            if (pUpdate.get(j).getVariable().equals(o)) {  //数据集合遍历查询跟那个相等
                                String str = pUpdate.get(j).getVariable();




                                // 查询缓存
                                String skuKey = "pol:" + o + ":lock";
                                String skuJson = jedis.get(skuKey);
                                if (StringUtils.isNotBlank(skuJson)) {//相当于if(skuJson!=null&&!skuJson.equals(""))

                                } else {
                                    String OK = jedis.set("pol:" + o + ":lock", "1", "nx");
                                    PUpdate pUpdate1 = updateMapper.selectByVariable1(str);//str是表明 变量名
                                    PUpdate pUpdate2 = updateMapper.selectByVariable2(str);
                                    PUpdate pUpdate3 = updateMapper.selectByVariable3(str);

                                    String groups1 = pUpdate1.getGroups();
                                    String groups2 = pUpdate2.getGroups();
                                    String groups3 = pUpdate3.getGroups();


                                    Double plimit1 = Double.valueOf(pUpdate1.getPlimit()).doubleValue();//报警限值
                                    Double plimit2 = Double.valueOf(pUpdate2.getPlimit()).doubleValue();
                                    Double plimit3 = Double.valueOf(pUpdate3.getPlimit()).doubleValue();

                                    if(pUpdate1.getLevels().equals("1")&&valuess>plimit1){
                                        System.err.println("开启紧急报警: " + "数据库=" + o + " 报警value值=" + value);

                                        mapper.insert(blname, "1",
                                                groups1, "1", svalue, pUpdate1.getPlimit(),
                                                pUpdate1.getRecovery(), pUpdate1.getDescribes(), data, "4");
                                    }
                                    else if(pUpdate2.getLevels().equals("2")&&valuess>plimit2){
                                        System.err.println("开启重要报警: " + "数据库=" + o + " 报警value值=" + value);

                                        mapper.insert(blname, "2",
                                                groups2, "2", svalue, pUpdate2.getPlimit(),
                                                pUpdate2.getRecovery(), pUpdate1.getDescribes(), data, "4");
                                    }
                                    else if(pUpdate3.getLevels().equals("3")&&valuess>plimit3){
                                        System.err.println("开启一般报警: " + "数据库=" + o + " 报警value值=" + value);

                                        mapper.insert(blname, "3",
                                                groups3, "3", svalue, pUpdate3.getPlimit(),
                                                pUpdate2.getRecovery(), pUpdate1.getDescribes(), data, "4");
                                    }

                                }
                                jedis.close();
                            }



//                        System.err.println(point.toString());
                            trackPoints.add(point);
                        }
                    }
                }

            }
//            System.err.println("points:"+trackPoints.toString());

        }
//        return trackPoints.toString();
        long date1 = new Date().getTime();
        System.err.println("开始= "+date);
        System.err.println("结束= "+date1);
        System.err.println(date1-date);

    }












    public  void variable(Object o, double value) {

        String blname = String.valueOf(o);  //变量名字是数据库名
        String svalue = String.valueOf(value);  //查询的报警value值
        Date data = new Date();
        Jedis jedis = redisUtil.getJedis();


        List<PUpdate> pUpdate = updateMapper.selectAll();

        for (int j = 0; j < pUpdate.size(); j++) {
        if (pUpdate.get(j).getVariable().equals(o)) {  //数据集合遍历查询跟那个相等
            String str = pUpdate.get(j).getVariable();




            // 查询缓存
            String skuKey = "pol:" + o + ":lock";
            String skuJson = jedis.get(skuKey);
            if (StringUtils.isNotBlank(skuJson)) {//相当于if(skuJson!=null&&!skuJson.equals(""))

            } else {
                String OK = jedis.set("pol:" + o + ":lock", "1", "nx");
                PUpdate pUpdate1 = updateMapper.selectByVariable1(str);//str是表明 变量名
                PUpdate pUpdate2 = updateMapper.selectByVariable2(str);
                PUpdate pUpdate3 = updateMapper.selectByVariable3(str);

                String groups1 = pUpdate1.getGroups();
                String groups2 = pUpdate2.getGroups();
                String groups3 = pUpdate3.getGroups();


                Double plimit1 = Double.valueOf(pUpdate1.getPlimit()).doubleValue();//报警限值
                Double plimit2 = Double.valueOf(pUpdate2.getPlimit()).doubleValue();
                Double plimit3 = Double.valueOf(pUpdate3.getPlimit()).doubleValue();

                if(pUpdate1.getLevels().equals("1")&&value>plimit1){
                    System.err.println("开启紧急报警: " + "数据库=" + o + " 报警value值=" + value);

                    mapper.insert(blname, "1",
                            groups1, "1", svalue, pUpdate1.getPlimit(),
                            pUpdate1.getRecovery(), pUpdate1.getDescribes(), data, "4");
                }
                else if(pUpdate2.getLevels().equals("2")&&value>plimit2){
                    System.err.println("开启重要报警: " + "数据库=" + o + " 报警value值=" + value);

                    mapper.insert(blname, "2",
                            groups2, "2", svalue, pUpdate2.getPlimit(),
                            pUpdate2.getRecovery(), pUpdate1.getDescribes(), data, "4");
                }
                else if(pUpdate3.getLevels().equals("3")&&value>plimit3){
                    System.err.println("开启一般报警: " + "数据库=" + o + " 报警value值=" + value);

                    mapper.insert(blname, "3",
                            groups3, "3", svalue, pUpdate3.getPlimit(),
                            pUpdate2.getRecovery(), pUpdate1.getDescribes(), data, "4");
                }

            }

        }

        }

        jedis.close();




    }


























}
